//
//  BleRootViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/6.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "BleRootViewController.h"

@interface BleRootViewController ()

@end

@implementation BleRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    baby = [BabyBluetooth shareBabyBluetooth];
//    //设置蓝牙委托
//    [self babyDelegate];
//    //设置委托后直接可以使用，无需等待CBCentralManagerStatePoweredOn状态
//    baby.scanForPeripherals().connectToPeripherals().begin();
    
    self.title = @"SITABLE";
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    scanBtn.frame = CGRectMake(0, 0, 40, 40);
    [scanBtn setTitle:@"扫描" forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanPeripheralsAction:) forControlEvents:UIControlEventTouchUpInside];
    [scanBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:scanBtn];
    self.navigationItem.rightBarButtonItem = barBtn;
    
    peripherals = [NSMutableArray arrayWithCapacity:1];
    
    /*
     设置主设备的委托,CBCentralManagerDelegate
     必须实现的：
     - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变的委托，在初始化CBCentralManager的适合会打开设备，只有当设备正确打开后才能使用
     其他选择实现的委托中比较重要的：
     - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设的委托
     - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
     - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
     - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
     */
    //初始化并设置委托和线程队列，最好一个线程的参数可以为nil，默认会就main线程
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}



-(void)scanPeripheralsAction:(UIButton *)btn
{
    //扫描蓝牙设备
    //开始扫描周围的外设
    /*
     第一个参数nil就是扫描周围所有的外设，扫描到外设后会进入
     - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
     */
    //NSLog(@"扫描到设备");
    [manager scanForPeripheralsWithServices:nil options:nil];
    
}




-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            break;
        default:
            break;
    }
}

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"当扫描到设备:%@",peripheral.name);
    NSString *peripheralName =peripheral.name;
    if (peripheral.name.length!=0) {
        if (peripherals.count==0) {
            [peripherals addObject:peripheral];
        }
        
        for ( int i = 0; i<peripherals.count; i++) {
            CBPeripheral *perir = [peripherals objectAtIndex:i];
            NSString *  oldperipheralName = perir.name;
            if ([peripheralName isEqualToString:oldperipheralName]) {
                
            }else{
                [peripherals addObject:peripheral];
            }
        }
    }
    
    [baseTableView reloadData];
    //接下来可以连接设备
    
    //peripheralVc
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return peripherals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    CBPeripheral *peripheral =[peripherals objectAtIndex:indexPath.row];
    cell.textLabel.text = peripheral.name;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   CBPeripheral *peripheral =[peripherals objectAtIndex:indexPath.row];
   [manager connectPeripheral:peripheral options:nil];
    
}


//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>连接到名称为（%@）的设备-成功",peripheral.name);
    
    PeripheralInfoViewController *peripheralVc =   [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"peripheralVc"];
    peripheralVc.peripheral =peripheral;
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
    temporaryBarButtonItem.title = @"";
    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:peripheralVc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>连接到名称为（%@）的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}



//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
    
}





////设置蓝牙委托
//-(void)babyDelegate{
//    __block BOOL isFirst = YES;
//    [baby setFilterOnConnectToPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
//        ;
//        if(isFirst && [peripheralName hasPrefix:@"BSK"]){
//            isFirst = NO;
//            return YES;
//        }
//        return NO;
//    }];
//    
//    
//    __block BleRootViewController *babyvc = self;
//    
//    [baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
//        ;
//        babyvc->baby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
//        .readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
//      
//    }];
//    
//    
////    //设置发现设备的Services的委托
//    [baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
//        for (CBService *s in peripheral.services) {
//            //每个service
//            NSLog(@"%@",s.peripheral.name);
//        }
//    }];
////
////    
////    [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
////        NSLog(@"===service name:%@",service.UUID);
////    }];
////    
////    
//    //设置读取characteristics的委托
//    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
//        currentCharacteristic=characteristics;
//        Byte b = 0X01;
//        NSData *data = [NSData dataWithBytes:&b length:sizeof(b)];
//        
//        [[babyvc->baby findConnectedPeripheral:@"BSKY"] writeValue:data forCharacteristic:characteristics type:CBCharacteristicWriteWithResponse];
//        
//          [[babyvc->baby findConnectedPeripheral:@"BSKY"] writeValue:data forCharacteristic:characteristics type:CBCharacteristicWriteWithResponse];
//       
//    }];
//    
//    
//    
//    
////    //设置发现characteristics的descriptors的委托
////    [baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
////        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
////        for (CBDescriptor *d in characteristic.descriptors) {
////            NSLog(@"CBDescriptor name is :%@",d.UUID);
////        }
////    }];
//    //设置读取Descriptor的委托
//    Byte b = 0X01;
//    NSData *data = [NSData dataWithBytes:&b length:sizeof(b)];
//    [baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
//        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
//        
//        [[babyvc->baby findConnectedPeripheral:@"BSKY"] writeValue:data forDescriptor:descriptor];
//    }];
//    
////    [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
////        NSLog(@"RSSI:%@",RSSI);
////    }];
//    
//   // NSLog(@"******:%@",currentCharacteristic);
//    
//    [baby setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
//        
//        ;
//    }];
//    
//    [baby setBlockOnDidWriteValueForDescriptor:^(CBDescriptor *descriptor, NSError *error) {
//        ;
//    }];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)startEnginAction:(UIButton *)sender
{
    
}
@end
